package zj.xinxin.business.business.articale;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import zj.xinxin.api.moudle.article.api.CategoryService;
import zj.xinxin.api.moudle.article.dto.CategoryDto;
import zj.xinxin.api.moudle.article.entity.CategoryEntity;
import zj.xinxin.api.moudle.article.vo.CategoryPageSearchVo;
import zj.xinxin.api.moudle.article.vo.CategoryVo;
import zj.xinxin.business.business.articale.converter.CategoryConverter;
import zj.xinxin.common.result.PageResult;
import zj.xinxin.common.utils.BeanCopyUtil;
import zj.xinxin.mapper.mapper.article.CategoryMapper;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 分类  服务实现类
 * </p>
 *
 * @author zhoujun
 * @since 2022-04-12
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, CategoryEntity> implements CategoryService {

    @Override
    public Boolean addByVo(CategoryVo categoryVo) {
        if (Objects.isNull(categoryVo)) {
            return Boolean.FALSE;
        }
        if (Objects.isNull(categoryVo.getParentId())) {
            categoryVo.setParentId(0L);
        }
        return this.saveOrUpdate(CategoryConverter.INSTANCE.toEntity(categoryVo));
    }

    @Override
    public PageResult<CategoryDto> searchCategoryByPage(CategoryPageSearchVo search) {
        Map<String, Object> parameter = BeanCopyUtil.objectToMap(search);
        IPage<CategoryEntity> categoryEntityIPage = this.baseMapper.searchPageByCondition(
                new Page<>(search.getCurrent(), search.getSize()), parameter);
        IPage<CategoryDto> result = categoryEntityIPage
                .convert(CategoryConverter.INSTANCE::toDto);

        return new PageResult<>(result.getRecords(), result.getTotal());
    }

    @Override
    public List<CategoryDto> listRoot() {
        return this.baseMapper.getRootList().stream()
                .map(CategoryConverter.INSTANCE::toDto)
                .collect(Collectors.toList());
    }
}
